package proxyhoster;

import static proxyhoster.AccessChecker.*;

import com.google.appengine.api.datastore.DatastoreService;
import com.google.appengine.api.datastore.DatastoreServiceFactory;
import com.google.appengine.api.datastore.Entity;
import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;

import java.io.IOException;
import java.util.Date;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

@SuppressWarnings("serial")
public class SignHostServlet extends HttpServlet {
	
	private static final Logger log = Logger.getLogger(SignHostServlet.class.getName()); 
	
	public void doGet(HttpServletRequest req, HttpServletResponse resp)
            throws IOException {
		
		log.info("doGet");
		resp.setContentType("text/plain");
		resp.getWriter().println("SignHostServlet.doGet()");
	}
	
	public void doPost(HttpServletRequest req, HttpServletResponse resp)
                throws IOException {
    	/*
        UserService userService = UserServiceFactory.getUserService();
        User user = userService.getCurrentUser();
        */
		log.info("doPost");

        String secureCode = req.getParameter("secureCode");
        if (!doCheck(secureCode)){
        	log.info("Secure Check Failed");
        	return;
        }
        
        /*
			com.google.appengine.codelab.Util
			persistEntity() method saves the entity using the datastore service put() API.
			deleteEntity() method deletes the entiry using the datastore service delete() API.
			findEntity() method searches the datastore given a key usign the datastore service find() API.
			listEntities() methods allows to search by adding filters through Query class. Executes the query using prepare. Prepare also returns an iterator.
         */
        
        String appName = req.getParameter("appName");
        Key appHostKey = KeyFactory.createKey("ApplicationHost", appName);
        
        String ip4Address = req.getRemoteAddr();
        String port = req.getParameter("port");
        Date date = new Date();
        
        Entity applicationHost = new Entity("ApplicationHost", appHostKey);
        applicationHost.setProperty("ip4Address", ip4Address);
        applicationHost.setProperty("port", port);
        applicationHost.setProperty("date", date);
        
        DatastoreService datastore = DatastoreServiceFactory.getDatastoreService();
        datastore.put(applicationHost);
        
        resp.sendRedirect("/applications.jsp?appName=" + appName);
    }
}
